import { Button, Card, Form, Input, Table, Tag } from 'antd'
import { useLocation,useNavigate } from 'react-router-dom'
import React, { SetStateAction, useEffect, useState } from 'react'
import {PlusOutlined,FormOutlined,DeleteOutlined} from "@ant-design/icons"
import { attrListItemType, attrValueListType, requestUpdateOrAddAttr } from '@/api/product';
export default function AddUpdata() {
    const columns = [
        {
          title: '序号',
          dataIndex: 'name',
          render:(_:any,__:any,index:any)=>{
            return index+1
          }
        },
        {
          title: '属性名称',
          dataIndex: 'valueName',
          key: 'valueName',
          render:(_:any,data:any)=>{
            if(data.isEdit){
                return <Tag onClick={()=>changeIsShow(data.id)} >{data.valueName} </Tag>
            }else{
                return <Input   value={data.valueName} onChange={changeValue}  onBlur={overOnBlur} autoFocus/>
            }
          }
        },
        {
          title: '操作',
          dataIndex: 'address',
          key: 'address',
          render:(_:any,data:any)=>{
            return <Button type="default" danger icon={<DeleteOutlined />}  onClick={()=>deleteattrItem(data.id)}></Button>
          }
        },
      ];
    const location = useLocation()
    const navigate = useNavigate()
    //属性名的数据
    const [attrName,setAttrName] = useState()
    //属性名称 的数据
    const [attrValueList,setAttrValueList] = useState<attrValueListType[]>([])
    //当前属性id的数据
    const [categoryId,setCategoryId] = useState()
      //categoryLevel
    const [categoryLevel,setCategoryLevel] = useState(3)
    //id
    const [ID,setID] = useState()
    const [currentId,setcurrentId] = useState<number>()
    //1.初始化的时候接受数据
    useEffect(()=>{ 

        if((location.state as any).attrName){
          //修改请求
    
        //设置路由传参属性名
        setAttrName((location.state as any).attrName.attrName)
        //设置路由传参属性名称列表
        setAttrValueList((location.state as any).attrName.attrValueList)
        //设置路由传参attrName
        setCategoryId((location.state as any).attrName.categoryId)
        //设置categoryLevel
        setCategoryLevel((location.state as any).attrName.categoryLevel)
        //设置ID
        setID((location.state as any).attrName.id)
        }else{
          //新增请求
          const id = +location.search.split("=")[1]    
          setCategoryId(id as any)
        }
    },[])
    //2.属性名input值变化之后
    const changeInput=(e:any)=>{
        //设置inputvalue
        setAttrName(e.target.value)
    }
    //3.点击添加属性
    const additem=()=>{
        //点击新增
        const attrlist = {
            id:Date.now(),
            valueName:"",
            attrId:ID,
            isEdit:false
        }
         //点击添加属性-增加新属性
        setAttrValueList([...attrValueList,attrlist])
        setcurrentId(attrlist.id)
    }
    //4.点击tag变成input
    const  changeIsShow =(id:any)=>{
        const newAttrValueList =attrValueList.filter(item=>{
            return item.id===id
        })
        // console.log(newAttrValueList);
        newAttrValueList[0].isEdit = false
        const newattr = attrValueList.map(item => {
          //实现排他
          if(item.id ===newAttrValueList[0].id){
            item = newAttrValueList[0]
          }else{
            item.isEdit=true
          }
          return item
        });
        // console.log(newattr);
        //是在修改哪一个数据
        setcurrentId(id)
        setAttrValueList(newattr)
    }
    //5.原始input数据发生改变之后的请求
    const changeValue = (e:any)=>{
      // console.log(e.target.value);
      // console.log(currentId);
      //首先找到当前数据
      const newlist = attrValueList.map(item=>{
        if(item.id ===currentId){
          item.valueName =e.target.value
        }
        return item
      })
      setAttrValueList(newlist)
    }
    //6.当失去焦点之后触发回调
    const overOnBlur = ()=>{
      //让所有的isEdit为true
      const newList = attrValueList.map(item=>{
        item.isEdit = true
        return item
      })
      setAttrValueList(newList)
    }
    //7.点击删除删除对应的一项
    const deleteattrItem =(id:number)=>{
      //删除对应的一项
      const  newList =  attrValueList.filter(item=>item.id!==id )
      setAttrValueList(newList)
    }

    //8.点击保存发送请求
    const save= async ()=>{
      //整合数据 发送请求
      const newAttr = {
        id: ID,
        attrName:attrName as unknown as string,
        categoryId: categoryId as unknown as number,
        categoryLevel : categoryLevel as unknown as number,
        attrValueList
      }
      await requestUpdateOrAddAttr(newAttr)
      navigate("/syt/product/attr")
    }
  return (
    <div>
        <Card >
            <Form
                  name="basic"
                  labelCol={{ span: 2 }}
                  wrapperCol={{ span: 5 }}
                  initialValues={{ remember: true }}
                >
                  <Form.Item
                    label="属性名"
                  >
                    <Input onChange={changeInput} value={attrName}/>
                  </Form.Item>
                    <Button type="primary" onClick={additem}>添加属性值</Button>
                    <Button type="default" style={{ margin: '0 15px' }}  onClick={()=>{navigate(-1)}}>取消</Button>
                </Form>
                <br />

                <Table 
                bordered
                dataSource={attrValueList} 
                columns={columns}
                pagination={false}
                rowKey="id"
                />
                <br />
                <br />
                <Button type="primary"  onClick={save}>保存</Button>
                <Button type="default" style={{ margin: '0 15px' }}  onClick={()=>{navigate(-1)}}>取消</Button>
        </Card>
    </div>
  )
}
